// src/composables/useDoubleClickEditing.ts
import { ref, nextTick } from 'vue';
import { useTemplateStore } from '@/stores/templateStore';
import type { TemplateElement } from '@/stores/templateStore';
import type { KonvaEventObject } from 'konva/lib/Node';
import type { Ref } from 'vue';

export function useDoubleClickEditing(stageRef: Ref<any>, transformerRef: Ref<any>) {
    const store = useTemplateStore();

    const isEditing = ref(false);
    const editingText = ref('');
    const textareaStyle = ref({});
    const editingTextarea = ref<HTMLTextAreaElement | null>(null);
    let editingNode: any = null;

    const handleDblClick = (elementData: TemplateElement, event: KonvaEventObject<MouseEvent>) => {
        const textNode = event.target;
        editingNode = textNode;

        textNode.hide();
        transformerRef.value?.getStage()?.hide();

        editingText.value = elementData.text || '';

        const textPosition = textNode.absolutePosition();
        const stageBox = stageRef.value.getStage().container().getBoundingClientRect();
        const areaPosition = {
            x: stageBox.left + textPosition.x,
            y: stageBox.top + textPosition.y,
        };

        textareaStyle.value = {
            position: 'absolute',
            top: `${areaPosition.y}px`,
            left: `${areaPosition.x}px`,
            width: `${textNode.width() * textNode.scaleX()}px`,
            height: `${textNode.height() * textNode.scaleY() + 5}px`, // 加一点高度防止文字被裁切
            fontSize: `${textNode.fontSize() * textNode.scaleY()}px`,
            lineHeight: textNode.lineHeight(),
            fontFamily: textNode.fontFamily(),
            transformOrigin: 'left top',
            transform: `rotate(${textNode.rotation()}deg)`,
            border: '1px solid #007bff',
            padding: '0px',
            margin: '0px',
            overflow: 'hidden',
            background: 'white',
            outline: 'none',
            resize: 'none',
            color: 'black',
        };

        isEditing.value = true;

        nextTick(() => {
            editingTextarea.value?.focus();
            editingTextarea.value?.select();
        });
    };

    const handleTextareaBlur = () => {
        if (!isEditing.value || !editingNode) return;

        store.updateElement(editingNode.id(), { text: editingText.value });

        isEditing.value = false;
        editingNode.show();
        transformerRef.value?.getStage()?.show();
        editingNode = null;
    };

    // 返回组件需要的所有状态和方法
    return {
        isEditing,
        editingText,
        textareaStyle,
        editingTextarea,
        handleDblClick,
        handleTextareaBlur,
    };
}